package com.ckd.flyingtrip.charge.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.activity.BaseActivity;
import com.ckd.flyingtrip.charge.javabean.CabinetListBean;
import com.ckd.flyingtrip.charge.javabean.OvertimeOrderBean;
import com.ckd.flyingtrip.charge.javabean.ProgressOrderBean;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.MapHelper;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.ckd.flyingtrip.activity.MainActivity.MAP_ZOOM_DEFAULT;

/*
 * 充电柜
 * */
public class MapActivity extends BaseActivity {

    @BindView(R.id.toolber_color_title)
    TextView title;
    @BindView(R.id.toolber_color_right)
    TextView right;
    @BindView(R.id.bmapView)
    MapView mMapView;
    @BindView(R.id.rl_ordering)
    RelativeLayout rlOrdering;
    //百度地图
    private BaiduMap mBaiduMap;
    //经纬度
    private Double firsLongitude = 0.0, firstLatitude = 0.0;
    //地图中心
    private LatLng mapCenterLatLng;
    //防止每次定位都重新设置中心点和marker
    private boolean aBoolean = true;
    private LocationClient mLocationClient;
    // 充电柜点
    private List<LatLng> list_Charging = new ArrayList<LatLng>();
    //    保存站点数据
    private List<CabinetListBean> listCity = new ArrayList<CabinetListBean>();
    private Map<String, CabinetListBean> cityMapZddm = new HashMap<>();
    private Marker mMarkerA = null;
    private List<Marker> markers = new ArrayList<>();
    //    mark文件
    private MarkerOptions option;

    //判断是否有未完成订单
    private String orderCode;
    private String orderMsg;
    private String orderState;  // 1充电中  2充满  3电池已取走
    private String orderMoney;  //待支付金额
    private String orderTime;    //超时时间
    private String orderType;  //电池类型 ( 0 磷酸铁锂电池、1 铅酸电池)
    private String orderV;     //电池电压 ( 48、60、72)

    //开门
    private String opeanCode; //  1柜门打开  0失败
    private String opeanMsg;
    private int num = 0 ;


    //机柜码
    private String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_code);
        ButterKnife.bind(this);

        initView();
        initOrder();
        initMapBaidu();
        getLocation();
        initMapLocation();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        initOrder();
        super.onResume();

    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initOrder();
    }


    private void initView() {
        title.setText("充电柜");
        right.setVisibility(View.VISIBLE);
        right.setText("充电订单");
    }

    //判断是否有未完成订单
    private void initOrder() {
        final Gson mGson = new Gson();
        String url = Constants.order_xcx;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("判断订单", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    orderCode = json.getString("code");
                    orderMsg = json.getString("msg");

                    if (orderCode.equals("1")) {
                        ProgressOrderBean bean = new Gson().fromJson(s, ProgressOrderBean.class);

                        rlOrdering.setVisibility(View.VISIBLE);
                        orderState = bean.getData().getState();
                        orderType = bean.getData().getBatteryType();
                        orderV = bean.getData().getBatteryV();
                        orderTime = bean.getData().getOvertime();
                        orderMoney = bean.getData().getMoney();

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    //开门
    private void initOpenDoor() {
        final Gson mGson = new Gson();
        String url = Constants.putBattery;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("开门", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    opeanCode = json.getString("code");
                    opeanMsg = json.getString("msg");

                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("cabinet", "CDZD08KXHD190401298");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    /*
     * 根据经纬度获取站点信息
     * */

    public void volleyZhandian(LatLng mapCenterLatLng) {
        final Gson mGson = new Gson();
        String url = Constants.getsitelist_xcx;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("获取站点信息", s);
                //s为请求返回的字符串数据
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        JSONArray data = json.getJSONArray("data");

                        if (data.length() > 0) {
                            list_Charging.clear();
                            cityMapZddm.clear();
                            listCity.clear();
                            for (int i = 0; i < data.length(); i++) {
                                String srt = String.valueOf(data.getJSONObject(i));
                                CabinetListBean city = mGson.fromJson(srt, CabinetListBean.class);
                                Log.i("城市位置信息", city.toString());
                                listCity.add(city);
                                try {
                                    LatLng l = new LatLng(Double.parseDouble(city.getLatitude()), Double.parseDouble(city.getLongitude()));
                                    list_Charging.add(l);
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                    toast("数据解析失败");
                                }
                                cityMapZddm.put(city.getSiteNum(), city);
                            }
                            Log.i("listCity", listCity.get(0).toString());
                            Log.i("list_LatLng", list_Charging.get(0).toString());
                            mBaiduMap.clear();
//                            checkRoute(false);
                            startMapAction(false);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创0建请求参数

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("latitude", mapCenterLatLng.latitude);
                    json_url.put("longitude", mapCenterLatLng.longitude);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }


    /*
     * 初始化地图配置
     * */
    private void initMapBaidu() {

        mMapView.showZoomControls(false);
        mMapView.showScaleControl(false);
        mBaiduMap = mMapView.getMap();

        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                MapView.setMapCustomEnable(true);
            }
        });

        // 隐藏logo
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setTrafficEnabled(false);
        mBaiduMap.setBuildingsEnabled(false);

        BaiduMap.OnMapStatusChangeListener listener = new BaiduMap.OnMapStatusChangeListener() {
            /**
             * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
             *
             * @param status 地图状态改变开始时的地图状态
             */
            @Override
            public void onMapStatusChangeStart(MapStatus status) {
                Log.e("sss", "---------------onMapStatusChangeStart");
                firsLongitude = status.target.longitude;
                firstLatitude = status.target.latitude;
            }

            /**
             * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
             *
             * @param status 地图状态改变开始时的地图状态
             *
             * @param reason 地图状态改变的原因
             */
            //用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
            //int REASON_GESTURE = 1;
            //SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
            //int REASON_API_ANIMATION = 2;
            //开发者调用,导致的地图状态改变
            //int REASON_DEVELOPER_ANIMATION = 3;
            @Override
            public void onMapStatusChangeStart(MapStatus status, int reason) {
                Log.e("sss", "---------------onMapStatusChangeStart----------" + reason);
            }

            /**
             * 地图状态变化中
             *
             * @param status 当前地图状态
             */
            @Override
            public void onMapStatusChange(MapStatus status) {
                Log.e("sss", "---------------onMapStatusChange");
            }

            /**
             * 地图状态改变结束
             *
             * @param status 地图状态改变结束后的地图状态
             */
            @Override
            public void onMapStatusChangeFinish(MapStatus status) {
                Log.e("sss", "---------------onMapStatusChangeFinish");
                // 只监听用户手势引起的地图状态变化
                System.out.println("调用了请求获取站点信息");

                mapCenterLatLng = new LatLng(status.target.latitude, status.target.longitude);
                if (aBoolean == true) {
                    volleyZhandian(mapCenterLatLng);
                    aBoolean = false;
                }

                if (firsLongitude == 0.0 || firstLatitude == 0.0)
                    return;
                Double aDouble = MapHelper.distance(firsLongitude, firstLatitude, status.target.longitude, status.target.latitude);
                Log.e("sss", "距离：" + aDouble);
                if (aDouble < 8) {
                    return;
                }
                firsLongitude = 0.0;
                firstLatitude = 0.0;

                volleyZhandian(mapCenterLatLng);

            }
        };

        ////设置地图状态监听
        mBaiduMap.setOnMapStatusChangeListener(listener);
    }


    // 开始地图相关动作
    private void startMapAction(boolean isNeedMove) {
        // 获取坐标点(模拟，实际为后台返回坐标，需异步加载)
        // getPoints();
        // 根据点绘制Marker

        showLineMarker();
    }


    /**
     * 根据坐标点绘制Marker
     */
    @SuppressLint("InflateParams")
    private void showLineMarker() {
        Log.i("sizeList", list_Charging.size() + "");
        Log.i("sizeList", listCity.size() + "");
        markers.clear();
        for (int i = 0; i < list_Charging.size(); i++) {
            // 构建marker图标
            View view_mark = LayoutInflater.from(MapActivity.this).inflate(R.layout.layout_map_maker, null);
            CabinetListBean zdjgFormBean = listCity.get(i);
            if (zdjgFormBean == null) {
                return;
            }
            ImageView ivBattery = (ImageView) view_mark.findViewById(R.id.iv_battery);
            ivBattery.setImageResource(R.mipmap.exchange);

            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view_mark);
            // 构建MarkerOption，用于在地图上添加Marker
            option = new MarkerOptions().icon(bitmap).position(list_Charging.get(i));
            // 设置marker里面的信息
            mMarkerA = (Marker) (mBaiduMap.addOverlay(option));
            markers.add(mMarkerA);
            mMarkerA.setPerspective(true);
            mMarkerA.setToTop();
            mMarkerA.setFlat(true);
            mMarkerA.setTitle(zdjgFormBean.getSiteNum());
            // 设置Marker覆盖物的ZIndex
            option.zIndex(999);
        }
    }

    private void getLocation() {
        // 获取位置管理服务
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) this.getSystemService(serviceName);
        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        //设置是否要求速度
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
        /**这段代码不需要深究，是locationManager.getLastKnownLocation(provider)自动生成的，不加会出错**/
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PERMISSION_GRANTED) {
            // TODO: Consider calling
            // ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            // public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //           int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
        updateLocation(location);

    }

    private void updateLocation(Location location) {
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
//            Toast.makeText(this, "经度" + latitude + "纬度" + longitude, Toast.LENGTH_SHORT).show();
            LatLng pos = new LatLng(latitude, longitude);
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(pos).zoom(MAP_ZOOM_DEFAULT);
            //镜头转至定位点
            MapStatusUpdate mapStatusUpdate =
                    MapStatusUpdateFactory.newMapStatus(builder.build());
            mBaiduMap.animateMapStatus(
                    mapStatusUpdate);

            volleyZhandian(pos);

        } else {
//            Toast.makeText(this, "无法获取到位置信息", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 初始化地图定位
     */

    private void initMapLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);// //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        // .getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIgnoreKillProcess(false); //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        option.setAddrType("all");
        option.setProdName("ipark");
        mLocationClient.setLocOption(option);
        mLocationClient.start();

    }

    /*
     * 跳转二维码界面
     * */
    private void tzErweima() {
        Intent intent = new Intent(MapActivity.this, CaptureActivity.class);
        ZxingConfig config = new ZxingConfig();
        config.setShowAlbum(false);
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, Constants.ZXINGE_MAIN);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == Constants.ZXINGE_MAIN && resultCode == RESULT_OK) {
            if (data != null) {
                //content所需机柜码
                content = data.getStringExtra(Constant.CODED_CONTENT);

                if (num == 0){
                    Intent intent = new Intent(MapActivity.this, BatteryInformationActivity.class);
                    startActivityForResult(intent, 1000);
                }else {
                    initOpenDoor();  //支付未开门,请重新扫码
                    toast(opeanMsg);
                }


//                try {
//                    JSONObject dataJson = new JSONObject(content);
//                    String code = dataJson.getString("code");
//                    Log.i("扫描结果为JSON", code);
//
////                    volleErweima(code);
//                } catch (JSONException e) {
//                    e.printStackTrace();
////                    volleErweima(content);
//                }
            }
        }
    }

    @OnClick({R.id.toolber_color_back, R.id.toolber_color_right, R.id.rl_charge, R.id.tv_ordering})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolber_color_back:
                finish();
                break;
            case R.id.toolber_color_right:
                Intent intent = new Intent(MapActivity.this, ChargeOrderActity.class);
                startActivity(intent);
                break;
            case R.id.rl_charge:
                if (orderCode.equals("0")){
                    tzErweima();
                }else {
                    switch (orderState){
                        case "1":
                        case "2":
                            toast(orderMsg);
                            break;
                        case "3":
                            tzErweima();
                            break;
                        case "0":
                            if (num == 0){
                                toast("支付未开门,请重新扫码");
                                num = 1;
                            }else{
                                tzErweima();
                            }
                            break;
                    }
                }
                break;
            case R.id.tv_ordering:
                Intent intent1 = new Intent(MapActivity.this, OrderInformationActivity.class);
                intent1.putExtra("orderType",orderType);
                intent1.putExtra("orderV",orderV);
                intent1.putExtra("orderMoney",orderMoney);
                intent1.putExtra("orderTime",orderTime);
                startActivity(intent1);
                break;
        }
    }

}
